package com.ruoyi.rms.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.rms.domain.WxUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.nio.cs.ext.MacGreek;

import java.io.IOException;

@RestController
@RequestMapping("/rms/wx")
public class WxController {

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    /**
     * 微信小程序登录
     * @param code
     * @return
     */
    @GetMapping("/login/{code}")
    public AjaxResult login(@PathVariable("code") String code) {
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("登录失败，编码不能为空");
        }

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=authorization_code";

        String openid = httpRequest(url, "openid");
        if (ObjectUtils.isEmpty(openid)) return AjaxResult.error("获取openid失败");

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid +
                "&secret=" + secret;

        String accessToken = httpRequest(tokenUrl, "access_token");
        if (ObjectUtils.isEmpty(accessToken)) return AjaxResult.error("获取access_token失败", openid);

        String msgUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
                + accessToken
                + "&openid=" + openid
                + "&lang=zh_CN";
        WxUser wxUser = httpRequest(msgUrl, openid, accessToken);
        if (ObjectUtils.isEmpty(wxUser)) return AjaxResult.error("获取用户信息失败", openid);

        return AjaxResult.success(wxUser);
    }

    /**
     * 发送请求获取字符串信息
     */
    private String httpRequest(String url, String name) {
        // 创建client请求
        CloseableHttpClient client = HttpClientBuilder.create().build();
        // 创建http请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求
        CloseableHttpResponse response = null;

        try {
            response = client.execute(httpGet);
            assert response != null;
            String result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(result);
            return jsonObject.getString(name);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 发送请求获取微信用户信息
     */
    private WxUser httpRequest(String url, String openid, String accessToken) {
        // 创建client请求
        CloseableHttpClient client = HttpClientBuilder.create().build();
        // 创建http请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求
        CloseableHttpResponse response = null;

        try {
            response = client.execute(httpGet);
            assert response != null;
            String result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(result);
            String nickName = jsonObject.getString("nickname");
            String sex = jsonObject.getString("sex");
            String city = jsonObject.getString("city");
            String province = jsonObject.getString("province");
            String country = jsonObject.getString("country");
            return new WxUser(openid, accessToken, nickName, sex, city, province, country);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
